package com.persistencia;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

/**
 * The Class BDDPersistence.
 * 
 * @param <T>
 *            the generic type
 */
public class BDDPersistence<T> implements Persistence<T> {
	private static final String PERSISTENCE_UNIT_NAME = "montranPU";
	private EntityManagerFactory factory;
	private EntityManager em;

	public BDDPersistence() {
		super();
		factory = javax.persistence.Persistence
				.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
		em = factory.createEntityManager();

	}

	@Override
	public Boolean create(T entidad) {
		try {

			em.getTransaction().begin();
			em.persist(entidad);
			em.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e);
		}

		return false;
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll(Class<T> classType) {
		List<T> list = new ArrayList<T>();
		try {
			em.getTransaction().begin();
			String name = "SELECT e FROM " + classType.getSimpleName() + " e";
			Query query = em.createQuery(name);
			list = query.getResultList();
			em.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e);
		}
		// em.close();
		return list;
	}

	public T findById(Class<T> classType, Long id) {
		T obj = null;
		try {
			em.getTransaction().begin();
			obj = em.find(classType, id);
			em.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e);

		}
		return obj;
	}

	@Override
	public Boolean update(T entidad) {
		try {
			em.getTransaction().begin();
			em.merge(entidad);
			em.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e);
		}

		return false;
	}

	@Override
	public Boolean delete(String id) {
		try {

			Object obj = findById(id);
			if (obj != null) {
				em.getTransaction().begin();
				em.remove(obj);
				em.getTransaction().commit();
			} else {
				return false;
			}

			return true;
		} catch (Exception e) {
			System.out.println(e);

		}

		return false;
	}

	@Override
	public List<T> findAll() {
		throw new UnsupportedOperationException();
	}

	@Override
	public T findById(String id) {
		throw new UnsupportedOperationException();
	}

}
